/*
 * File:         Purchase.java
 * Author:       Robert Bittle <guywithnose@gmail.com>
 */
package faceBook;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.logging.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
import foxtrotbravo.DataConnection;
import foxtrotbravo.DataObject;

/**
 * The Class Message.
 */
public class Purchase implements DataObject, JSONString
{

  /** The Constant log. */
  private static final Logger log = Logger.getLogger(Purchase.class
      .getName());

  /** The ID. */
  private long ID;

  /** The user. */
  private User user;

  /** The price. */
  private double price;
  
  /** The message count. */
  private int messageCount;
  
  /** The time. */
  private Timestamp time;

  /** The order id. */
  private long orderId;

  /**
   * Instantiates a new message.
   */
  public Purchase()
  {
  }

  /**
   * Instantiates a new message.
   * 
   * @param id
   *          the id
   */
  public Purchase(long id)
  {
    ID = id;
    load();
  }
  
  /**
   * Get User.
   *
   * @return the user
   */
  public User getUser()
  {
    return user;
  }

  /**
   * Sets the user.
   *
   * @param USER the new user
   */
  public void setUser(User USER)
  {
    this.user = USER;
  }

  /**
   * Get Price.
   *
   * @return the price
   */
  public double getPrice()
  {
    return price;
  }

  /**
   * Sets the price.
   *
   * @param Price the new price
   */
  public void setPrice(double Price)
  {
    this.price = Price;
  }

  /**
   * Get Message count.
   *
   * @return the message count
   */
  public int getMessageCount()
  {
    return messageCount;
  }

  /**
   * Sets the message count.
   *
   * @param MessageCount the new message count
   */
  public void setMessageCount(int MessageCount)
  {
    this.messageCount = MessageCount;
  }

  /**
   * Get Time.
   *
   * @return the time
   */
  public Timestamp getTime()
  {
    return time;
  }

  /**
   * Sets the time.
   *
   * @param Time the new time
   */
  public void setTime(Timestamp Time)
  {
    this.time = Time;
  }

  /**
   * Get Order id.
   *
   * @return the order id
   */
  public long getOrderId()
  {
    return orderId;
  }

  /**
   * Sets the order id.
   *
   * @param OrderId the new order id
   */
  public void setOrderId(long OrderId)
  {
    this.orderId = OrderId;
  }

  /**
   * Get ID.
   *
   * @return the ID
   */
  public long getID()
  {
    return ID;
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.json.JSONString#toJSONString()
   */
  @Override
  public String toJSONString()
  {
    return toJSONObject().toString();
  }

  /**
   * To json object.
   * 
   * @return the jSON object
   */
  public JSONObject toJSONObject()
  {
    JSONObject JO = new JSONObject();
    try
    {
      JO.put("ID", ID);
      JO.put("user", user);
      JO.put("price", price);
      JO.put("messageCount", messageCount);
      JO.put("time", time);
      JO.put("orderId", orderId);
    } catch (JSONException e)
    {
      // Do Nothing
    }
    return JO;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString()
  {
    return toJSONString();
  }

  /*
   * (non-Javadoc)
   * 
   * @see foxtrotbravo.DataObject#save()
   */
  @Override
  public boolean save()
  {
    try
    {
      if (ID != 0)
      {
        return update();
      }
      return insert();
    } catch (SQLException e)
    {
      e.printStackTrace();
    }
    return false;
  }

  /*
   * (non-Javadoc)
   * 
   * @see foxtrotbravo.DataObject#load()
   */
  @Override
  public boolean load()
  {
    try
    {
      if (DataConnection.connect())
      {
        String statement = "select user, price, messageCount, time, orderId from purchase where id = ?";
        PreparedStatement stmt = DataConnection.getConnection()
            .prepareStatement(statement);
        stmt.setLong(1, ID);
        ResultSet results = stmt.executeQuery();
        if (results.next())
        {
          user = new User(results.getLong("user"));
          price = results.getFloat("price");
          messageCount = results.getInt("messageCount");
          time = results.getTimestamp("time");
          orderId = results.getLong("orderId");
          return true;
        }
      }
    } catch (SQLException e)
    {
      e.printStackTrace();
    }
    return false;
  }

  /*
   * (non-Javadoc)
   * 
   * @see foxtrotbravo.DataObject#delete()
   */
  @Override
  public boolean delete()
  {
    try
    {
      if (DataConnection.connect())
      {
        String statement = "delete from purchase where id = ?";
        PreparedStatement stmt = DataConnection.getConnection()
            .prepareStatement(statement);
        stmt.setLong(1, ID);
        int success = 2;
        success = stmt.executeUpdate();
        return success == 1;
      }
    } catch (SQLException e)
    {
      e.printStackTrace();
    }
    return false;
  }

  /**
   * Update.
   * 
   * @return true, if successful
   * @throws SQLException
   *           the SQL exception
   */
  private boolean update() throws SQLException
  {
    if (DataConnection.connect())
    {
      String statement = "update purchase set user = ?, price = ?, messageCount = ?, time = ?, orderId = ? where id = ?";
      PreparedStatement stmt = DataConnection.getConnection().prepareStatement(
          statement);      
      
      stmt.setLong(1, user.getID());
      stmt.setDouble(2, price);
      stmt.setInt(3, messageCount);
      stmt.setTimestamp(4, time);
      stmt.setLong(5, orderId);
      stmt.setLong(6, ID);
      int success = 2;
      success = stmt.executeUpdate();

      return success == 1;
    }
    return false;
  }

  /**
   * Insert.
   * 
   * @return true, if successful
   * @throws SQLException
   *           the sQL exception
   */
  private boolean insert() throws SQLException
  {
    log.info("New purchase : " + toString());
    if (DataConnection.connect())
    {
      String statement = "INSERT INTO purchase (user, price, messageCount, time, orderId) VALUES ( ?, ?, ?, ?, ? )";
      PreparedStatement stmt = DataConnection.getConnection().prepareStatement(
          statement, Statement.RETURN_GENERATED_KEYS);
      stmt.setLong(1, user.getID());
      stmt.setDouble(2, price);
      stmt.setInt(3, messageCount);
      stmt.setTimestamp(4, time);
      stmt.setLong(5, orderId);
      int success = 2;
      success = stmt.executeUpdate();
      ResultSet key = stmt.getGeneratedKeys();
      if (key.next())
      {
        ID = key.getLong(1);
      }
      return success == 1;
    }
    return false;
  }

  /**
   * Get All purchases for user.
   *
   * @param user the user
   * @return the all purchases for user
   */
  public static int getMessageCountForUser(User user)
  {
    try
    {
      if (DataConnection.connect())
      {
        String statement = "select sum(messageCount) as count from purchase where user = ?";
        PreparedStatement stmt = DataConnection.getConnection()
            .prepareStatement(statement);
        stmt.setLong(1, user.getID());
        ResultSet results = stmt.executeQuery();
        if (results.next())
        {
          return results.getInt("count");
        }
      }
    } catch (SQLException e)
    {
      e.printStackTrace();
    }
    return 0;
  }

}
